import math

from flask import Blueprint, request, make_response, jsonify, redirect
import json, random, time, requests
from utils.myredis import r
from models.models import *

need_blue = Blueprint("needblue", __name__)


@need_blue.route("/getclose")
# 支付方式
def getclose():
    close = Close.query.all()
    lst = []
    for i in close:
        lst.append({
            "id": i.id,
            "name": i.name,
            "described": i.described
        })
    return jsonify({"code": 200, "msg": "获取成功", "data": lst})


@need_blue.route("/getneed")
# 获取需求类型
def getneed():
    label = Need_kind.query.all()
    lists = []
    list_one = []
    for i in label:
        # 获取所有pid==0的数据
        if i.pid == 0:
            # 判断时候在list_one列表中
            if i.id not in list_one:
                # 将pid==0的数据加入到lists总
                lists.append({'id': i.id, 'name': i.name, 'son': []})
                list_one.append([i.id])
    for j in label:
        for index, p in enumerate(lists):
            # 判断所有数据的pid是否等于lists中的id，将等于的数据加入到lists中的son中
            if j.pid == p['id']:
                lists[index]['son'].append({'id': j.id, 'name': j.name, 'tow_son': []})
    for s in label:
        for index, p in enumerate(lists):
            aa = lists[index]['son']
            for indexa, a in enumerate(aa):
                if s.pid == a['id']:
                    aa[indexa]['tow_son'].append({'id': s.id, 'name': s.name})
    return jsonify({"code": 200, "data": lists})


@need_blue.route("/gettalents")
# 获取人才类型
def gettalents():
    label = Talents.query.all()
    lists = []
    list_one = []
    for i in label:
        # 获取所有pid==0的数据
        if i.pid == 0:
            # 判断时候在list_one列表中
            if i.id not in list_one:
                # 将pid==0的数据加入到lists总
                lists.append({'id': i.id, 'name': i.name, 'son': []})
                list_one.append([i.id])
    for j in label:
        for index, p in enumerate(lists):
            # 判断所有数据的pid是否等于lists中的id，将等于的数据加入到lists中的son中
            if j.pid == p['id']:
                lists[index]['son'].append({'id': j.id, 'name': j.name, 'tow_son': []})
    for s in label:
        for index, p in enumerate(lists):
            aa = lists[index]['son']
            for indexa, a in enumerate(aa):
                if s.pid == a['id']:
                    aa[indexa]['tow_son'].append({'id': s.id, 'name': s.name})
    return jsonify({"code": 200, "data": lists})


# 启动雪花算法
# snowflake_start_server --worker=1
import snowflake.client


def create_ordercode(tablename, count):
    # 雪花算法生成唯一id
    code = snowflake.client.get_guid()
    # 用redis解决始终回拨，根据key查询上一次存入的结果，
    # 和当前生成的对比，如果当前小于redis中存储的，说明发生时钟回拨
    # 先取
    value = r.str_get(tablename)
    # 判断是否存在
    if value:
        # 当前时间 小于 redis中存储的时间
        if int(code) < int(value):
            # 重新调用  雪花算法生成唯一id
            create_ordercode(tablename, count)
    # 把最后一次生成的存入redis
    r.set_str(tablename, code)
    # 取模获取列表
    number = hash(code) % int(count)
    print("表", number)
    if number == 0:
        return tablename, code
    else:
        return tablename + str(number), code


@need_blue.route("/setneed", methods=["POST"])
# 发布需求
def setneed():
    data = json.loads(request.data)
    closeid = data["closeid"]
    title = data["title"]
    described = data["described"]
    money = data["money"]
    userid = data["userid"]
    tablename, code = create_ordercode('Need', 3)
    # 发布需求的金额必须大于用户金额
    res1 = User.query.filter_by(id=userid).first()
    if int(res1.money) < int(money):
        return jsonify({"code": 400, "msg": "金币不足"})
    # 转为表明
    tablename1 = globals().get(f'{tablename}')
    if not all([closeid, title, described, money, userid]):
        return jsonify({"code": 400, "msg": "字段不能为空"})
    if closeid == 1:
        needid = data["needid"]
        # 修改金额/锁定金额
        user = User.query.filter_by(id=userid).first()
        if user:
            # print(user.locks)
            user.locks = float(user.locks) + float(money)
            user.money = float(user.money) - float(money)
            db.session.add(user)
            need = tablename1(code=code, closeid=closeid, title=title, described=described, needid=needid, money=money,
                              userid=userid, status=1)
            db.session.add(need)
            db.session.commit()
            r.list_push("needs", code)
            return jsonify({"code": 200, "msg": "发布成功待审核"})
    if closeid == 2:
        # 修改金额/锁定金额
        user = User.query.filter_by(id=userid).first()
        if user:
            user.locks = float(user.locks) + float(money)
            user.money = float(user.money) - float(money)
            db.session.add(user)
            talentsid = data["talentsid"]
            need = tablename1(code=code, closeid=closeid, title=title, described=described, talentsid=talentsid,
                              money=money, userid=userid, status=1)
            db.session.add(need)
            db.session.commit()
            r.list_push("needs", code)
            return jsonify({"code": 200, "msg": "发布成功待审核"})
    return jsonify({"code": 400, "msg": "请选择计费方式"})


@need_blue.route("/sneed")
# 获取审核过的需求
# 分页优化
def sneed():
    page = int(request.args.get("page"))
    # 每页显示多少条
    page_size = int(request.args.get("page_size"))
    # redis str
    key = "need" + str(page)
    totalkey = "need_total"
    list = r.str_get(key)
    lst = []
    total = []
    if list:
        lst = json.loads(list)
        total = int(r.str_get(totalkey).decode())
        print("redis缓存")
    else:
        print("mysql获取")
        # 获取总记录数
        need = db.session.execute(
            "select count(code) as a  from (select * from need where status=2 union all select * from need1 where status=2 union all select * from need2 where status=2) as t order by code desc")
        for i in need:
            total.append(i.a)
        # print("total",total)
        # 获取当前页面的数据 在查询的时候加一个where条件
        if page > 1:
            # 获取前一页的最大id page-1
            pages = page - 1
            pmes = r.str_get("need" + str(pages))
            if pmes:
                # 最最后一条的id
                mm = json.loads(pmes)
                for i in mm[-1:]:
                    preid = i["code"]
                # preid = mm[-1:]["code"]
                csql = db.session.execute(
                    "select * from (select * from need where status=2 union all select * from need1 where status=2 union all select * from need2 where status=2) as t where code<'%s' order by code desc limit %d,%d" % (
                    preid, 0, page_size))
                if csql:
                    for i in csql:
                        lst.append({
                            'code': str(i.code),
                            'title': i.title,
                            "money": i.money,
                            "described": i.described,
                            "closeid": i.closeid,
                            "userid": i.userid
                        })
            else:
                start = (page - 1) * page_size
                csql = db.session.execute(
                    "select * from (select * from need where status=2 union all select * from need1 where status=2 union all select * from need2 where status=2) as t order by code desc limit %d,%d" % (
                    start, page_size))
                if csql:
                    for i in csql:
                        lst.append({
                            'code': str(i.code),
                            'title': i.title,
                            "money": i.money,
                            "described": i.described,
                            "closeid": i.closeid,
                            "userid": i.userid
                        })
        else:
            start = (page - 1) * page_size
            csql = db.session.execute(
                "select * from (select * from need where status=2 union all select * from need1 where status=2 union all select * from need2 where status=2) as t order by code desc limit %d,%d" % (
                start, page_size))
            if csql:
                for i in csql:
                    lst.append({
                        'code': str(i.code),
                        'title': i.title,
                        "money": i.money,
                        "described": i.described,
                        "closeid": i.closeid,
                        "userid": i.userid
                    })
        # 加入缓存
        # print("lst",lst)
        r.str_add(key, json.dumps(lst))
        for i in total:
            r.str_add(totalkey, i)
    return jsonify({"code": 200, "msg": "获取成功", "data": lst, "total": total})


@need_blue.route("/needall")
# 交易成功需求
def needall():
    page = request.args.get("page")
    page_size = request.args.get("page_size")
    need = db.session.query(Need).filter(Need.status == 5)
    need1 = db.session.query(Need1).filter(Need1.status == 5)
    need2 = db.session.query(Need2).filter(Need2.status == 5)
    start = (int(page) - 1) * int(page_size)
    ret = need.union(need1).union(need2).offset(start).limit(page_size).all()  # 数据重复，只留一条
    lists = []
    for i in ret:
        lists.append({
            'code': str(i.code),
            'title': i.title,
            "money": i.money,
            "described": i.described,
            "closeid": i.closeid,
            "userid": i.userid
        })
    # 总数据量
    total = need.union(need1).union(need2).count()
    return jsonify({"code": 200, "msg": "获取成功", "data": lists, "total": total})


@need_blue.route("/need_close")
# 外包/计时
def need_close():
    page = request.args.get("page")
    page_size = request.args.get("page_size")
    closeid = request.args.get("closeid")
    start = (int(page) - 1) * int(page_size)
    need = db.session.query(Need).filter(Need.closeid == closeid, Need.status == 5)
    need1 = db.session.query(Need1).filter(Need1.closeid == closeid, Need1.status == 5)
    need2 = db.session.query(Need2).filter(Need2.closeid == closeid, Need2.status == 5)
    ret = need.union(need1).union(need2).offset(start).limit(page_size).all()  # 数据重复，只留一条
    lists = []
    for i in ret:
        lists.append({
            'code': str(i.code),
            'title': i.title,
            "money": i.money,
            "described": i.described,
            "closeid": i.closeid,
            "userid": i.userid
        })
    total = need.union(need1).union(need2).count()
    return jsonify({"code": 200, "msg": "获取成功", "data": lists, "total": total})

# 需求详情页
@need_blue.route("/need_xq")
def need_xq():
    code = request.args.get("code")
    need = db.session.query(Need).filter(Need.code == code)
    need1 = db.session.query(Need1).filter(Need1.code == code)
    need2 = db.session.query(Need2).filter(Need2.code == code)
    ret = need.union(need1).union(need2).all()
    lst = []
    for i in ret:
        lst.append({
            'code': str(i.code),
            'title': i.title,
            "money": i.money,
            "described": i.described,
            "closeid": i.closeid,
            "userid":i.userid
        })
    return jsonify({"code": 200, "data": lst})

# @need_blue.route('/label_index')
# 查询
# def label_index():
#     input = request.args.get('input')
#     lst = []
#     res = Need.query.filter(Need.title.ilike(f"%{input}%")).all()
#     if res:
#         lst.append(res)
#     ress = Need1.query.filter(Need1.title.ilike(f"%{input}%")).all()
#     if ress:
#         lst.append(ress)
#     resa = Need2.query.filter(Need2.title.ilike(f"%{input}%")).all()
#     if resa:
#         lst.append(resa)
#     new_list = [j for i in lst for j in i]
#     lists = []
#     if new_list:
#         for s in new_list:
#             lists.append({
#                 'code': str(s.code),
#                 'title': s.title,
#                 "money": s.money,
#                 "described": s.described,
#                 "closeid": s.closeid,
#                 "userid": s.userid
#             })
#         return jsonify({
#             'code': 200,
#             'msg': "OK",
#             "data":lists
#         })
#     else:
#         return jsonify({
#             'code': 400,
#             'msg': "数据不存在"
#         })





